package Servlet;

import Entity.Player;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This servelet is called during registration of new user accounts.
 * It checks if the username exists prior to registry.
 * If the username exists, it returns an INVALID entity.
 * If the username does not exist, it registers the new user.
 *
 * @author Rodge Uy
 */
@PersistenceContext(name = "persistence/LogicalName", unitName = "GooWherePU")
public class PlayerRegisterServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute("loginInfo", setRegister(request.getParameter("userName"),request.getParameter("email"),request.getParameter("passWord")));

        // Now that the controller has gathered the data from the model,
        // pass the data onto the view to render it as JSON.
        RequestDispatcher view = request.getRequestDispatcher("/login_view.jsp");
        view.forward(request, response);
        
    }

    private List<Map<String, String>> setRegister(String userName, String email, String passWord) {
        List<Map<String, String>> login = new ArrayList<Map<String, String>>();

        try {

            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //try to find the username in the database first
            Query q = em.createNamedQuery("Player.findByPlayName").setParameter("playName", userName);
            List<Player> nameresults = q.getResultList();

            //if the username is in the database, return invalid because registration has failed
            if (!(nameresults.isEmpty())){
                Map<String, String> clue = new HashMap<String, String>();
                clue.put("userName", "INVALID");
                clue.put("passWord", "INVALID");
                login.add(clue);
            }
            //username does not exist, register user
            else if (nameresults.isEmpty()){

                //default user starts off with level 1, 0 accumulated score, no picture, and offline.
                Player p = new Player(userName, 1, 0, passWord, email, 0, 0);
                persist(p);

            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
            
        }
        return login;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    protected void persist(Object object) {
        try {
            Context ctx = GetContext.getContext();
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }
}
